package com.sywb.chuangyebao.contract;

import android.Manifest;
import android.graphics.drawable.Drawable;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.sywb.chuangyebao.Constants;
import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.bean.OpenAd;
import com.sywb.chuangyebao.library.player.PlayerUtils;
import com.sywb.chuangyebao.utils.HttpCallback;
import com.sywb.chuangyebao.utils.HttpUtils;
import com.sywb.chuangyebao.view.GuideActivity;
import com.sywb.chuangyebao.view.MainAtlasActivity;
import com.sywb.chuangyebao.view.WebActivity;

import org.bining.footstone.log.Logger;
import org.bining.footstone.mvp.IView;
import org.bining.footstone.presenter.PermissionsPresenter;
import org.bining.footstone.rxjava.rxbus.RxBus;
import org.bining.footstone.utils.ApkUtils;
import org.bining.footstone.utils.SharedUtils;

public interface SplashContract {

    interface SplashView extends IView {

        TextView getJumpView();

        ImageView getAdView();
    }

    class Presenter extends PermissionsPresenter<SplashView> {

        Handler mHandler = new Handler();

        private OpenAd openA;

        private TextView jumpView;
        private ImageView imageView;

        private CountDownTimer timer;

        private boolean isPermissions = false;
        private boolean isCountDown = false;

        @Override
        public void onStart() {
            jumpView = mView.getJumpView();
            imageView = mView.getAdView();

            jumpView.setVisibility(View.GONE);

            PlayerUtils.setUseTrafficPlay(false);
            questPermissions(new String[]{Manifest.permission.WRITE_SETTINGS, Manifest.permission.CHANGE_NETWORK_STATE, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION});

            getPic();
        }

        private void addClickNum(int id) {
            HttpUtils.adClick(id, new HttpCallback<String>() {
                @Override
                public void onSuccess(String s) {
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                }
            });
        }

        @Override
        public void onPermissionsSuccess(String[] strings) {
//            mHandler.postDelayed(new MyRunnable(), 1000);
            isPermissions = true;
            if (isCountDown) {
                toIntentOther();
            }
        }

        @Override
        public void onPermissionsFailure(String strMsg) {
            super.onPermissionsFailure(strMsg);
            showMessage(strMsg);
//            mHandler.postDelayed(new MyRunnable(), 1000);
            isPermissions = true;
            if (isCountDown) {
                toIntentOther();
            }
        }

        private void getPic() {
            final WindowManager manager = mActivity.getWindowManager();
            DisplayMetrics outMetrics = new DisplayMetrics();
            manager.getDefaultDisplay().getMetrics(outMetrics);
            String ratio = outMetrics.widthPixels + "x" + outMetrics.heightPixels;

            HttpUtils.getAd(null, new HttpCallback<OpenAd>() {
                @Override
                public void onSuccess(OpenAd openAd) {
                    if (openAd == null) {
                        return;
                    }
                    openA = openAd;

                    RequestOptions requestOptions = new RequestOptions();
                    requestOptions.placeholder(R.drawable.splash).error(R.drawable.splash).fallback(R.drawable.splash);

                    Glide.with(mActivity).load(openAd.android_picture_addr).apply(requestOptions).into(new SimpleTarget<Drawable>() {
                        @Override
                        public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                            imageView.setImageDrawable(resource);
                            jumpView.setVisibility(View.VISIBLE);
                            countDown();

                            imageView.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    if (openA == null) {
                                        return;
                                    }
                                    cancelCountDown();
                                    if (mView != null) {
                                        mView.advance(WebActivity.class, openA.title, openA.link_addr, null, true);
                                    }
                                    addClickNum(openA.id);
                                }
                            });
                        }

                        @Override
                        public void onLoadFailed(@Nullable Drawable errorDrawable) {
                            super.onLoadFailed(errorDrawable);
                            toIntentOther();
                        }
                    });

//                    GlideUtils.getNormalIamgeToUrl(mActivity, openAd.android_picture_addr, imageView, R.drawable.splash);
//                    jumpView.setVisibility(View.VISIBLE);
                }

                @Override
                public void onError(String strMsg) {
                    super.onError(strMsg);
                    toIntentOther();
                }
            });
        }

        private void countDown() {
            /** 倒计时3秒，一次1秒 */
            timer = new CountDownTimer(5000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    // TODO Auto-generated method stub
                    Logger.e("还剩" + millisUntilFinished / 1000 + "秒");
                }

                @Override
                public void onFinish() {
                    Logger.e("倒计时完毕了");
                    toIntentOther();
                }
            }.start();
        }

        public void cancelCountDown() {
            if (timer != null) {
                timer.cancel();
            }
        }

        public void toIntentOther() {
            isCountDown = true;
            if (!isPermissions) {
                return;
            }
            RxBus.get().post(Manifest.permission.WRITE_SETTINGS, Manifest.permission.WRITE_SETTINGS);
            int lastVersionCode = SharedUtils.getInt(Constants.LASTUSEVERSION, 0);
            int versionCode = ApkUtils.getVersionCode();
            if (lastVersionCode == 0 || lastVersionCode < versionCode) {
                if (lastVersionCode < 54) {
                    SharedUtils.put("home_title_selected", "");
                    SharedUtils.put("home_title_unselected", "");
                }

                SharedUtils.put(Constants.ISMESSAGENOTICE, true);
                SharedUtils.put(Constants.ISOPENSUOUND, true);
                SharedUtils.put(Constants.ISOPENVIBRATION, true);
                if (mView != null) {
                    mView.advance(GuideActivity.class);
                }
            } else {
                SharedUtils.put(Constants.LASTUSEVERSION, versionCode);
                if (mView != null) {
                    mView.advance(MainAtlasActivity.class);
                    //mView.advance(ManuscriptManagementActivity.class);
                }
            }
        }

//        private void CheckPermission() {
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                if (!Settings.System.canWrite(getActivity())) {
//                    ToastUtils.show(mActivity, "请在该设置页面勾选，才可以使用路况提醒功能");
//                    Uri selfPackageUri = Uri.parse("package:" + getActivity().getPackageName());
//                    Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS, selfPackageUri);
//                    startActivityForResult(intent, 100);
//                } else {
//                    RxBus.get().post(Manifest.permission.WRITE_SETTINGS, Manifest.permission.WRITE_SETTINGS);
//                    mHandler.postDelayed(new SplashActivity.MyRunnable(), 500);
//                }
//            } else {
//                RxBus.get().post(Manifest.permission.WRITE_SETTINGS, Manifest.permission.WRITE_SETTINGS);
//                mHandler.postDelayed(new SplashActivity.MyRunnable(), 500);
//            }
//        }

        class MyRunnable implements Runnable {
            @Override
            public void run() {
                toIntentOther();
            }
        }

    }
}

